﻿using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;

namespace Common
{
    /// <summary>
    /// 时间戳对象
    /// </summary>
    public class TimeStamp
    {
        private readonly DateTime _basicTime;
        private readonly DateTime utcNow;
        /// <summary>
        /// 时间戳
        /// </summary>
        public TimeStamp()
        {
            this.utcNow = DateTime.Now.ToUniversalTime();
            _basicTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        }
        private TimeStamp(long seconds)
            : this()
        {
            this.utcNow = _basicTime.AddSeconds(seconds);
        }
        private TimeStamp(DateTime time)
            : this()
        {
            this.utcNow = time.ToUniversalTime();
        }
        /// <summary>
        /// DateTime的隐式转换
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static implicit operator TimeStamp(DateTime time)
        {
            return new TimeStamp(time);
        }
        /// <summary>
        /// double的隐式转换
        /// </summary>
        /// <param name="seconds"></param>
        /// <returns></returns>
        public static implicit operator TimeStamp(long seconds)
        {
            return new TimeStamp(seconds);
        }
        /// <summary>
        /// 时间戳到double的隐式转换
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public static implicit operator long(TimeStamp ts)
        {
            if (ts == null)
                return 0;
            return ts.Seconds;
        }
        /// <summary>
        /// 毫秒
        /// </summary>
        public long MilliSeconds { get { return (long)(this.utcNow - this._basicTime).TotalMilliseconds; } }
        /// <summary>
        /// 秒数
        /// </summary>
        public long Seconds { get { return (long)(this.utcNow - this._basicTime).TotalSeconds; } }
        /// <summary>
        /// 时间戳对应的时间
        /// </summary>
        public DateTime LocalDate { get { return utcNow.ToLocalTime(); } }
        /// <summary>
        /// UTC时间
        /// </summary>
        public DateTime UtcDate { get { return this.utcNow; } }
        /// <summary>
        /// 当前时间戳
        /// </summary>
        public static TimeStamp Now => new TimeStamp(DateTime.Now);
    }
}
